<?php
    $context=$sf_context;
    if ($context->has("twig")){
        $twig=$context->get("twig");
        $templatePath=$context->get("twigTemplatePath");
    }else{
        $twigPluginDir=sfConfig::get('sf_plugins_dir')."/bertaTwigPlugin/";

        require_once("{$twigPluginDir}/lib/vendor/Twig/lib/Twig/Autoloader.php");
        Twig_Autoloader::register();

        // @todo dynamic template directory recognition here
        $templateSettings=TemplateSettings::getInstance();
        $templateDirectory=$templateSettings->getDirectoryName();

        if ($templateDirectory==""){
            $templateDirectory="default";
        }

        $templatePath="{$twigPluginDir}/templates/{$templateDirectory}/";

        $twig = new Twig_Environment(
            new Twig_Loader_Filesystem($templatePath),
            array(
                 "autoescape"   =>  false,
                 "auto_reload"  =>  true,
                 "cache"        =>  sfConfig::get('sf_cache_dir')."/bertaTwigPlugin/{$templateDirectory}/"
            )
        );


        require_once("{$twigPluginDir}/TwigExtensions/Extension/Text.php");

        $textExtension = new Twig_Extensions_Extension_Text();
        $twig->addExtension($textExtension);


        //	// berta model object sandbox
        //	$policyTags=array();
        //	$policyFilters=array();
        //
        //	// strtolower and no "get" prefix for names plskthnxbye
        //	// Doctrine magic properties - always permitted. but magic methods - NOT. go figure :\
        //	$policyMethods = array(
        //		"Section" => array(),
        //		"Tag" => array("url"),
        //		"Entry" => array("tags", "images", "url"),
        //		"EntryImage" => array("forgallery"),
        //		"asImage" => array("width", "height", "url"),
        //        "Widget" => array("t"),
        //        "WidgetPosition" => array("t"),
        //	);
        //	$policyProperties=array(
        //		"Settings" => "*",
        //		"ObjectForTwig" => "*",
        //        "Entry" => "*",
        //        "Widget" => "*",
        //        "WidgetPosition" => "*",
        //	);
        //
        //	require_once("Twig_Sandbox_SecurityPolicy_Berta.class.php");
        //	$policy = new Twig_Sandbox_SecurityPolicy_Berta($policyTags, $policyFilters, $policyMethods, $policyProperties);
        //
        //	$sandbox = new Twig_Extension_Sandbox($policy, true);
        //	$twig->addExtension($sandbox);

        $context->set("twig", $twig);
        $context->set("twigTemplatePath", $templatePath);
    }